#include <sys/types.h>
#include <sys/stat.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>

#include "listfile.h"


LISTFILE_STATIC int listfile_init(listfile_t * self, int fd)
{
	self->fd = fd;
	self->next_index = 0;
	if (fwindow_init(&self->head, fd, 1024*1024) != 0) {
		return -1;
	}
	return 0;
}

LISTFILE_STATIC int listfile_fini(listfile_t * self)
{
	if (fwindow_fini(&self->head) != 0) {
		return -1;
	}
	return 0;
}

LISTFILE_STATIC inline int listfile_append(listfile_t * self,
		const void * buffer, uint32_t size)
{
	int index = self->next_index;
	if (fwindow_write(&self->head, &size, sizeof(size)) != 0) {
		return -1;
	}
	if (fwindow_write(&self->head, buffer, size) != 0) {
		//self->head.pos -= sizeof(size); // correct position ?
		return -1;
	}
	self->next_index += 1;
	return index;
}

LISTFILE_STATIC inline off_t listfile_append2(listfile_t * self,
		const void * buffer, uint32_t size)
{
	off_t pos = self->head.pos;
	if (fwindow_write(&self->head, &size, sizeof(size)) != 0) {
		return -1;
	}
	if (fwindow_write(&self->head, buffer, size) != 0) {
		return -1;
	}
	return pos;
}

LISTFILE_STATIC int listfile_open(listfile_t * self, const char * filename)
{
	int ret = 0;
	int fd = open(filename, O_RDWR | O_CREAT | O_TRUNC,
			S_IWUSR | S_IRUSR | S_IRGRP | S_IROTH);
	RETURN_WITH_CODE_IF(LISTFILE_ERR_OPEN_FAILED, fd < 0);
	ret = listfile_init(self, fd);
	if (ret != 0) {
		close(fd);
		self->fd = -1;
	}
	return ret;
}

LISTFILE_STATIC int listfile_close(listfile_t * self)
{
	int ret = 0;
	ret = listfile_fini(self);
	if (self->fd >= 0) {
		close(self->fd);
		self->fd = -1;
	}
	return ret;
}






